<?php


namespace App\Rpc\client\impl;

use App\Common\RedisUtils;
use App\Common\Res;
use App\Common\StringUtils;
use App\Constants\ErrorCode;
use App\Model\form\UserDeviceTrait;
use App\Request\client\UserDeviceRequest;
use App\Rpc\client\UserDeviceInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use HyperfException\Json;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;


class UserDeviceImpl implements UserDeviceInterface
{
    use RedisUtils, UserDeviceTrait, StringUtils,Res;

    /**
     * 设备登录
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function login(array $params): array
    {
        ApplicationContext::getContainer()->get(UserDeviceRequest::class)->validated($params, 'appLogin');
        return Db::transaction(function () use ($params) {
            /*根据imei查询设备数据*/
            $device = $this->getUserDeviceInfo((string)$params['unionId']);
            if (empty($device))
                throw new json(ErrorCode::getMessage(ErrorCode::ERROR), ErrorCode::ERROR);
            /*删除redis原有token，记录新token*/
            $this->del('device_' . $device->token);
            /*更新账户token*/
            $device->token = $this->createDeviceToken((string)$params['unionId']);
            $device->update(['token' => $device->token]);
            /*存储新的redis*/
            $device = $device->toArray();
            $this->set('device_' . $device['token'], json_encode($device), 10080);
            return $this->Success('登录成功', $device);
        });
    }


    /**
     * 判断设备是否登录
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function isLogin(array $params): array
    {
        ApplicationContext::getContainer()->get(UserDeviceRequest::class)->validated($params, __FUNCTION__);
        /*根据token查询redis是否存在数据*/
        $isToken = $this->get('device_' . $params['token']);
        if (!$isToken)
            return $this->Error(ErrorCode::ERROR, "设备信息不存在");
        $device = json_decode($isToken, true);
        /*验证数据库里token是否存在*/
        /*更新redis过期时间*/
        $this->set('device_' . $params['token'], json_encode($device), 300);
        return $this->Success('验证成功', $device);
    }
}